<?php

/**
 * JingYao-backend
 *
 * @link     https://gitee.com/wang-zhihui-release/jingyao-backend
 * @apiDocument https://gitee.com/wang-zhihui-release/jingyao-backend/wikis/
 */

namespace App\Services;

use App\Enums\UserIdentityEnum;
use App\Exceptions\ApiException;
use App\Models\House;
use App\Models\HouserScore;
use App\Models\HouserScoreResult;
use App\Models\HouseUserBind;
use App\Models\User;
use App\Models\UserProfile;
use Illuminate\Support\Facades\DB;

class HouserService
{
    public function houserSort(int $page, int $pageSize, string $orderType, string $name)
    {
        if (empty($orderType)) {
            $orderType = 'desc';
        }
        $userIds = [];
        if (! empty($name)) {
            $userIds = User::query()->select('id')
                ->where('name', 'like', '%' . $name . '%')
                ->get()->pluck('id')->toArray();
        }
        $builder = HouserScoreResult::query();
        if (! empty($name)) {
            $builder->whereIn('houser_id', $userIds);
        }

        $count = $builder->count();

        $houserScores = $builder->orderBy('real_score', $orderType)
            ->skip(($page - 1) * $pageSize)->take($pageSize)->get()->toArray();

        $houserIds = array_column($houserScores, 'houser_id');
        $housers = UserProfile::query()->select('name', 'user_id')->whereIn('user_id', $houserIds)->get()->toArray();
        $houses = House::query()->select('houser_user_id', 'images')->whereIn('houser_user_id', $houserIds)->get()->toArray();
        $housersMap = array_column($housers, null, 'user_id');
        $housesMap = array_column($houses, null, 'houser_user_id');
        foreach ($houserScores as &$houserScore) {
            $houserScore['houser_name'] = $housersMap[$houserScore['houser_id']]['name'] ?? '';
            $houserScore['house_image'] = $housesMap[$houserScore['houser_id']]['images'][0] ?? '';
            $houserScore['render_score'] = caleRenderScore($houserScore['houser_score']);
            $houserScore['help_xcx'] = helpXcxRenderScore(caleRenderScore($houserScore['houser_score']));
            $houserScore['free_house_number'] = $this->getHouserFreeHouse($houserScore['houser_id']);
        }
        return [
            'count' => $count,
            'page' => $page,
            'page_size' => $pageSize,
            'list' => $houserScores,
        ];
    }

    public function deleteHouser(int $houserId)
    {
        /** @var UserProfile $userProfile */
        $userProfile = UserProfile::query()->where('user_id', $houserId)->first();
        if (empty($userProfile)) {
            throw new ApiException('用户不存在', 1);
        }
        if ($userProfile->identity != UserIdentityEnum::HOUSER) {
            throw new ApiException('此用户不是房东身份', 1);
        }
        DB::beginTransaction();
        try {
            // 用户信息退回居民
            $userProfile->identity = UserIdentityEnum::NORMAL;
            $userProfile->save();
            User::query()->where('id', $houserId)->update([
                'identity' => UserIdentityEnum::NORMAL,
            ]);
            $houseIds = House::query()
                ->where('houser_user_id', $houserId)
                ->select('id')
                ->get()
                ->pluck('id');
            // 删除租客绑定信息
            HouseUserBind::query()->whereIn('house_id', $houseIds)->delete();
            // 删除房屋评分
            HouserScore::query()->whereIn('house_id', $houseIds)->delete();
            // 删除房屋统计分数(房东排名)
            HouserScoreResult::query()->where('houser_id', $houserId)->delete();
            // 删除房屋信息
            House::query()->where('houser_user_id', $houserId)->delete();
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            throw new ApiException($e->getMessage(), 1);
        }
        return true;
    }

    private function getHouserFreeHouse(int $houserId)
    {
        return House::query()->where('houser_user_id', $houserId)->doesntHave('houseUserBind')->count();
    }
}
